package leetcode.code0684;

import leetcode.IDebug;

public class Solution implements IDebug {

	public int[] findRedundantConnection(int[][] edges) {
		int n = 1001;
		roots = new int[n];
		sizes = new int[n];
		for (int i = 0; i < n; i++) {
			roots[i] = i;
			sizes[i] = 1;
		}
		stack = new int[n];
		for (int i = 0; i < edges.length; i++) {
			int[] edge = edges[i];
			int a = edge[0], b = edge[1];
			if (this.isSameSet(a, b)) {
				return edge;
			}
			this.union(a, b);
		}
		return null;
	}

	int[] roots;
	int[] sizes;
	int[] stack;

	public int findRoot(int id) {
		int root = 0;
		int p = 0;
		while ((root = roots[id]) != id) {
			stack[p++] = id;
			id = root;
		}
		while (p > 0) {
			roots[stack[--p]] = root;
		}
		return root;
	}

	public boolean isSameSet(int id1, int id2) {
		return findRoot(id1) == findRoot(id2);
	}

	public void union(int id1, int id2) {
		int p1 = this.findRoot(id1);
		int p2 = this.findRoot(id2);
		if (p1 != p2) {
			int size1 = this.sizes[p1];
			int size2 = this.sizes[p2];
			if (size1 < size2) {
				this.roots[p1] = p2;
				this.sizes[p2] = size1 + size2;
				this.sizes[p1] = 0;
			} else {
				this.roots[p2] = p1;
				this.sizes[p1] = size1 + size2;
				this.sizes[p2] = 0;
			}
		}
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
